package panels;

import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.*;

import niso.*;

public class SalesPane extends JSplitPane implements ItemListener, ActionListener, FocusListener,KeyListener{

	
	private userFrame Parent;		
	private Date SelectedDate;
	private JButton ViewBt,UpdateBt,AddMode,Nextday,Prevday,Next,Prev,InsertInvoice,ResetInsert,DelInvoice,DebtCheck;
	private JComboBox DayBox,MonthBox,YearBox,InvoiceBox,EnterUnit,EnterProd;
	private CardLayout CL;
	private JPanel ViewPane,DebtPane;
	private GBPane NewSales;
	private JLabel Statuslbl,StatusAdd,DayLbl,MonthLbl,YearLbl,Limitlbl;
	private JTextField Customer,TotalBox,BalanceBox,NewCustomer,RNumBox,NewTotal,Newbal,EnterQuan,EnterPrice,LimBal;
	private ArrayList <Invoice>Invoices;
	private ArrayList<JTextField> QuantityBoxes,UnitBoxes,ProdBoxes,PriceBoxes,NewQuans,NewPrices;
	private ArrayList<JComboBox> AddUnits,AddProd;
	private Container Cnt=new Container();		//Contains the components at the right
        private Invoice Selected;
	
	public SalesPane(userFrame P){
		Parent=P;
		SelectedDate=new Date();
		
		ViewBt=new JButton("View Sales");
		UpdateBt=new JButton("Update Sales");
		DelInvoice=new JButton("Remove Invoice");   //Button for deleting invoice. Not in navigation
		AddMode=new JButton("Add Sales");           //Add sales here
		Nextday=new JButton("Next Day");
		Prevday=new JButton("Previous Day");
		Next=new JButton("Next");
		Prev=new JButton("Previous");
		DebtCheck=new JButton("Customers with balance");
		
		Statuslbl=new JLabel("");
		StatusAdd=new JLabel("");
		DayBox=new JComboBox();		//Combobox containing the  Selected day 
		MonthBox=new JComboBox();	//Combobox containing the  Selected Month
		YearBox=new JComboBox();	//Combobox containing the  Selected Year 
		InvoiceBox=new JComboBox();	//Combobox containing Sales record on the selected date
		
		
		generateUIComponents("SELECT * from Invoice where dateofReceipt=CurDate();");
		
		StatusAdd.setFont(Parent.getWarningFont(StatusAdd));
		ViewBt.addActionListener(this);
		UpdateBt.addActionListener(this);
		AddMode.addActionListener(this);
		Next.addActionListener(this);
		Prev.addActionListener(this);
		Prevday.addActionListener(this);
		Nextday.addActionListener(this);
		DelInvoice.addActionListener(this);
		
		DebtCheck.addActionListener(this);
        Customer.addFocusListener(this);
        ResetInsert.addActionListener(this);
        InsertInvoice.addActionListener(this);
        Customer.addKeyListener(this);
        TotalBox.addKeyListener(this);
        BalanceBox.addKeyListener(this);
        NewCustomer.addKeyListener(this);
        RNumBox.addKeyListener(this);
        RNumBox.addFocusListener(this);
        Newbal.addKeyListener(this);
        Newbal.addFocusListener(this);
	}
	
	public void generateUIComponents(String S){
		GBPane Nav,GBView,AddPane,BalPane;
		
		// Set navigation panel at the left
		Nav=new GBPane();
		Nav.addComponent(ViewBt, 0, 2, 1, 2, 0, 0, GridBagConstraints.VERTICAL, GridBagConstraints.WEST);
		if(Parent.getUser().getusertype()=="Owner"||Parent.getUser().getusertype()=="Manager"){
			Nav.addComponent(UpdateBt, 0, 4, 1, 2, 0, 0, GridBagConstraints.VERTICAL, GridBagConstraints.WEST);
			Nav.addComponent(AddMode, 0, 6, 1, 2, 0, 0, GridBagConstraints.VERTICAL, GridBagConstraints.WEST);
			Nav.addComponent(DebtCheck, 0, 8, 1, 2, 0, 0, GridBagConstraints.VERTICAL, GridBagConstraints.WEST);
		}
		setLeftComponent(Nav);	// The left side of the split pane will contain the navigation of the module
		
		CL=new CardLayout();
		Cnt.setLayout(CL);
		
		
		//Add the ui components to the Panel containing the receipts
		GBView=new GBPane();
		GBView.addComponent(new JLabel("<html><h1>Sales</h1></html>"), 3, 0, 2, 1, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
		GBView.addComponent(Statuslbl=new JLabel(""), 0, 14, 6, 1, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
		GBView.addComponent(Prevday, 0, 2, 1, 1, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
		GBView.addComponent(DayLbl=new JLabel("Day"), 1, 2, 1, 1, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
		GBView.addComponent(DayBox, 2, 2, 1, 1, 0, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
		GBView.addComponent(MonthLbl=new JLabel("Month"), 3, 2, 1, 1, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
		GBView.addComponent(MonthBox, 4, 2, 1, 1, 0, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
		GBView.addComponent(YearLbl=new JLabel("Year"), 5, 2, 1, 1, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
		GBView.addComponent(YearBox, 6, 2, 1, 1, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
		GBView.addComponent(Nextday, 7, 2, 1, 1, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
		
		GBView.addComponent(Prev, 2, 3, 1, 1, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
		GBView.addComponent(InvoiceBox, 3,3, 3, 1, 0, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
		GBView.addComponent(Next, 6, 3, 1, 1, 0, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
		
		Invoices=getDBItems(S);
		ViewPane=new JPanel();
		
		try{
			setComboBoxItems(MonthBox);
			setComboBoxItems(YearBox);
			AddInvoicestoCombobox();
		} catch(SQLException SqlEx){}
		

                    

		GBView.addComponent(new JLabel("Customer:"), 2, 4, 1, 1, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
		
		GBView.addComponent(new JLabel("Total:"), 2, 10, 1, 1, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
        GBView.addComponent(new JLabel("Balance:"), 2, 11, 1, 1, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
                if(Invoices.size()>0){
                    Selected=Invoices.get(0);
                    GBView.addComponent(Customer=new JTextField(Selected.getCustomerName()), 3, 4, 2, 1, 0, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
                    GBView.addComponent(TotalBox=new JTextField(Selected.getTotal()+""), 3, 10, 1, 1, 0, 0,GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
                    GBView.addComponent(BalanceBox=new JTextField(Selected.getBalance()+""), 3, 11, 1, 1, 0, 0,GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
                }
                else {
                    GBView.addComponent(Customer=new JTextField(5), 3, 4, 2, 1, 0, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
                    GBView.addComponent(TotalBox=new JTextField(5), 3, 10, 1, 1, 0, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
                    GBView.addComponent(BalanceBox=new JTextField(5), 3, 11, 1, 1, 0, 0,GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
                }
            
         GBView.addComponent(ViewPane, 0, 5, 8, 4, 0, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
         
         //Delete invoice is here but it it is visible in update
         GBView.addComponent(DelInvoice, 2, 12, 2, 2, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
        		RecordpaneConfig(0,false);
                Customer.setEditable(false);
                TotalBox.setEditable(false);
                BalanceBox.setEditable(false);
                DelInvoice.setVisible(false);
		
		Cnt.add("Manage", GBView);
		
		
		JTextField black=new JTextField(10);
		black.setEnabled(false);
		black.setBackground(Color.black);
		
		AddPane=new GBPane();		//Panel where new receipts can be made
		NewSales=new GBPane();		//Panel where a new sales transaction can be made
		
		//Add Components to add pane
		AddPane.addComponent(new JLabel("<html><h1>Insert Sales</h1></html>"), 3, 0, 2, 1, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
		AddPane.addComponent(black, 0, 3, 8, 1, 0, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
		AddPane.addComponent(StatusAdd, 0, 2, 4, 1, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
		AddPane.addComponent(new JLabel("Sold to"), 0, 4, 1, 1, 0, 0,GridBagConstraints.NONE, GridBagConstraints.WEST);
		AddPane.addComponent(NewCustomer=new JTextField(15), 1, 4, 3, 1, 0, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
		AddPane.addComponent(new JLabel("Invoice Number"), 5, 4, 1, 1, 0, 0,GridBagConstraints.NONE, GridBagConstraints.EAST);
		AddPane.addComponent(RNumBox=new JTextField(5), 6, 4, 2, 1, 0, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
		
		AddInvoiceConfig(NewSales);
		
		JScrollPane ScrollAdd=new JScrollPane(NewSales),ScrDebt;
		ScrollAdd.setPreferredSize(new Dimension(300, 300));
		
		AddPane.addComponent(ScrollAdd, 0, 5, 6, 4, 0, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
		
		AddPane.addComponent(new JLabel("Total "), 1, 11, 1, 2, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
		AddPane.addComponent(new JLabel("Balance "), 3, 11, 1, 2, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
		AddPane.addComponent(NewTotal=new JTextField("0"), 2, 11, 1, 1, 0, 0, GridBagConstraints.BOTH, GridBagConstraints.WEST);
		AddPane.addComponent(Newbal=new JTextField("0"), 4, 11, 1, 1, 0, 0, GridBagConstraints.BOTH, GridBagConstraints.WEST);
		
		Newbal.setEditable(false);
		NewTotal.setEditable(false);
		
		AddPane.addComponent(InsertInvoice=new JButton("Insert Receipt"), 2, 12, 1, 2, 0, 0, GridBagConstraints.BOTH, GridBagConstraints.WEST);
		AddPane.addComponent(ResetInsert=new JButton("Reset Form"), 4, 12, 1, 2, 0, 0, GridBagConstraints.BOTH, GridBagConstraints.WEST);
		
		
		InsertInvoice.setEnabled(false);
		Cnt.add("Add", AddPane);
		
		BalPane=new GBPane();
		DebtPane=new JPanel();
		ScrDebt=new JScrollPane(DebtPane);
		ScrDebt.setPreferredSize(new Dimension(300, 300));
		
		changeDebtPane(5000);
		BalPane.addComponent(Limitlbl=new JLabel("Limit"), 0, 2, 1, 1, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
		BalPane.addComponent(LimBal=new JTextField("5000"), 1, 2, 1, 1, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
		BalPane.addComponent(ScrDebt, 1, 3, 1, 4, 0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST);
		Cnt.add("Debt", BalPane);
		
		InvoiceBox.addItemListener(this);
		DayBox.addItemListener(this);
		MonthBox.addItemListener(this);
		YearBox.addItemListener(this);
		BalanceBox.addFocusListener(this);
		LimBal.addKeyListener(this);
		LimBal.addFocusListener(this);
		//setRightComponent(GBView);
		setRightComponent(Cnt);
	}
	
	//repaint all the other containers
	public void paintAnsestors(Container C){
		while(C.getParent()!=null){
			C.repaint();
			C=C.getParent();
		}
	}
	
	public ArrayList<Invoice> getDBItems(String s){
		ArrayList<Invoice> Records=new ArrayList<Invoice>();
		ResultSet RS,RInvoice;
		
		RInvoice=Parent.getDBHandler().MySQLSelect(s);
		
		try{
			while(RInvoice.next())
				Records.add(new Invoice(RInvoice.getString(1),RInvoice.getString(3),RInvoice.getString(2),RInvoice.getDouble(4)));
			
			RInvoice.close();
			
			for(int ctr=0;ctr<Records.size();ctr++){
				RS=Parent.getDBHandler().MySQLSelect("Select SaleID,Quantity, unit, productname, price from Sale,product where prCode=ProductCode AND ReceiptNum="+
						Records.get(ctr).getReceiptNum());
				while(RS.next())
					Records.get(ctr).addSale(new Sale(RS.getString(1),RS.getString(4),RS.getString(3),RS.getDouble(2),RS.getDouble(5)));
			}
		}catch (SQLException SQLe) {
			// TODO Auto-generated catch block
			Statuslbl.setFont(Parent.getWarningFont(Statuslbl));
			Statuslbl.setText("Error in Collecting Records");
		}
		
		
		return Records;
	}
	
	public ArrayList <String>getCustomerbal(String s,int i){
		ArrayList <String> L=new ArrayList();
		ResultSet RS;
		
		try{
			RS=Parent.getDBHandler().MySQLSelect(s);
			while(RS.next()){
				L.add(RS.getString(i));
			}
		}catch (SQLException SQLe) {
			// TODO Auto-generated catch block
			Statuslbl.setFont(Parent.getWarningFont(Statuslbl));
			Statuslbl.setText("Error in Collecting Records");
		}
		
		return L;
	}
	
	//Display the Sales in the receipt
	private void RecordpaneConfig(int n,boolean edit){
		ViewPane.removeAll();
		
		if(Invoices.size()>0){
		ViewPane.setLayout(new GridLayout(Invoices.get(n).getSales().size()+2, 4));
		ViewPane.add(new JLabel("Quantity"));
		ViewPane.add(new JLabel("Unit"));
		ViewPane.add(new JLabel("Product"));
		ViewPane.add(new JLabel("Price"));
		
		QuantityBoxes=new ArrayList<JTextField>();
		UnitBoxes=new ArrayList<JTextField>();
		ProdBoxes=new ArrayList<JTextField>();
		PriceBoxes=new ArrayList<JTextField>();
		
		
		Invoice I=Invoices.get(n);
			if(I!=null&&I.getCustomerName()!=null)
                Customer.setText(I.getCustomerName()+"");
			else  Customer.setText("");
                TotalBox.setText(""+I.getTotal());
                BalanceBox.setText(""+I.getBalance());
                
		for(int ctr=0;ctr<I.getSales().size();ctr++){
			QuantityBoxes.add(new JTextField(I.getSales().get(ctr).getQuantity()+""));
			UnitBoxes.add(new JTextField(I.getSales().get(ctr).getUnit()));
			ProdBoxes.add(new JTextField(I.getSales().get(ctr).getProduct()));
			PriceBoxes.add(new JTextField(I.getSales().get(ctr).getPrice()+""));
			
			ViewPane.add(QuantityBoxes.get(ctr));
			ViewPane.add(UnitBoxes.get(ctr));
			ViewPane.add(ProdBoxes.get(ctr));
			ViewPane.add(PriceBoxes.get(ctr));
			
			
			QuantityBoxes.get(ctr).setEditable(edit);
			UnitBoxes.get(ctr).setEditable(false);
			ProdBoxes.get(ctr).setEditable(false);
			PriceBoxes.get(ctr).setEditable(edit);
			
			QuantityBoxes.get(ctr).addFocusListener(this);
			UnitBoxes.get(ctr).addFocusListener(this);
			ProdBoxes.get(ctr).addFocusListener(this);
			PriceBoxes.get(ctr).addFocusListener(this);
			QuantityBoxes.get(ctr).addKeyListener(this);
			PriceBoxes.get(ctr).addKeyListener(this);
			}
		ViewPane.add(EnterQuan=new JTextField());
		ViewPane.add(EnterUnit=new JComboBox());
		ViewPane.add(EnterProd=new JComboBox());
		ViewPane.add(EnterPrice=new JTextField());
		
		EnterQuan.setEditable(edit);
		EnterUnit.setEnabled(edit);
		EnterProd.setEnabled(edit);
		EnterPrice.setEditable(false);
		
		EnterUnit.addActionListener(this);
		EnterProd.addActionListener(this);
		
		
		try {
			setComboBoxItems(EnterUnit);
			setComboBoxItems(EnterProd);
		} catch (SQLException e) {
			Statuslbl.setText("Erro in collecting data");
		}
		
		
		}
		else Statuslbl.setText("<html><h2>No Sales Listed today</h2></html>");
	}
	
	
	private void ChangeViewPaneContents(String S,boolean edit){
		
		Customer.setText("");	//Reset the textboxes to blanks
        TotalBox.setText("");
        BalanceBox.setText("");
		
		
		//get the records from the selected date
		Invoices=getDBItems(S);
		AddInvoicestoCombobox();			//Set the values of the combobox containing the Invoices
        RecordpaneConfig(0,edit);	//Display the Sales in the receipt
        NewSales.paintAncestors();
	}
	
	private void changeDebtPane(){
		ArrayList<String> L1=getCustomerbal("SELECT CustomerName,sum(RemainingBalance) from Invoice group by customername",1);
		ArrayList<String> L2=getCustomerbal("SELECT CustomerName,sum(RemainingBalance) from Invoice group by customername",2);
		DebtPane.removeAll();
		if(L1.size()>0){
			DebtPane.setLayout(new GridLayout(L1.size()+1,2));
			DebtPane.add(new JLabel("Customer Name"));
			DebtPane.add(new JLabel("Balance"));
			
			for(int ctr=0;ctr<L1.size();ctr++){
				DebtPane.add(new JLabel(L1.get(ctr)));
				DebtPane.add(new JTextField(L2.get(ctr)));
			}
			
		}
		
	}
	
	private void changeDebtPane(double d){
		ArrayList<String> L1=getCustomerbal("SELECT CustomerName,sum(RemainingBalance) from Invoice where RemainingBalance >="+d+"group by customername",1);
		ArrayList<String> L2=getCustomerbal("SELECT CustomerName,sum(RemainingBalance) from Invoice where RemainingBalance >="+d+"group by customername",2);
		DebtPane.removeAll();
		if(L1.size()>0){
			DebtPane.setLayout(new GridLayout(L1.size()+1,2));
			DebtPane.add(new JLabel("Customer Name"));
			DebtPane.add(new JLabel("Balance"));
			
			for(int ctr=0;ctr<L1.size();ctr++){
				DebtPane.add(new JLabel(L1.get(ctr)));
				DebtPane.add(new JLabel(L2.get(ctr)));
			}
			
		}
		
	}
	
	public void ManageViewPaneVisibility(boolean view){
		Prevday.setVisible(view);
		Nextday.setVisible(view);
		MonthLbl.setVisible(view);
		YearLbl.setVisible(view);
		DayBox.setVisible(view);
		MonthBox.setVisible(view);
		YearBox.setVisible(view);
		DayLbl.setVisible(view);
		
		if(InvoiceBox.getItemCount()>0)
		for(int ctr=0;ctr<Invoices.get(InvoiceBox.getSelectedIndex()).getSales().size();ctr++){
			QuantityBoxes.get(ctr).setEditable(!view);
			PriceBoxes.get(ctr).setEditable(!view);
		}
		
		Customer.setEditable(!view);
		BalanceBox.setEditable(!view);
		EnterQuan.setEditable(!view);
		EnterUnit.setEnabled(!view);
		EnterProd.setEnabled(!view);
		EnterPrice.setEditable(!view);
		DelInvoice.setVisible(!view);
	}
	
	public void setComboBoxItems(JComboBox cb) throws SQLException{
		cb.removeAllItems();
		if(cb==MonthBox){
			cb.addItem("January");cb.addItem("Febuary");cb.addItem("March");
			cb.addItem("April");cb.addItem("May");cb.addItem("June");
			cb.addItem("July");cb.addItem("August");cb.addItem("September");
			cb.addItem("October");cb.addItem("November");cb.addItem("December");
			
			ResultSet RS=Parent.getDBHandler().MySQLSelect("Select Month(now());"),RY,RD;
			RS.first();
			cb.setSelectedIndex(RS.getInt(1)-1);
			
			RY=Parent.getDBHandler().MySQLSelect("Select Year(now());");
			RY.first();
			
			int limit,ctr;
			
			if(RS.getInt(1)==1||RS.getInt(1)==3||RS.getInt(1)==5||RS.getInt(1)==7||RS.getInt(1)==8
					||RS.getInt(1)==10||RS.getInt(1)==12)
				limit=31;
			else if(RS.getInt(1)==2)
				if(RY.getInt(1)%4!=0)
					limit =28;
				else limit=29;
			else limit=30;
			
			for(ctr=1;ctr<=limit;ctr++)
				DayBox.addItem(""+ctr);
			RS.close();
			RY.close();
			
			
			RD=Parent.getDBHandler().MySQLSelect("Select Day(now());");
			RD.first();
			
			DayBox.setSelectedItem(RD.getString(1));
			RD.close();
			
			}
		else if(cb==YearBox){
			ResultSet RS=Parent.getDBHandler().MySQLSelect("Select Year(TimeRecorded) from Inventory group by year(TimeRecorded);");
			
			while(RS.next())
				cb.addItem(RS.getString(1));
			cb.setSelectedIndex(cb.getItemCount()-1);
			RS.close();
		}
		
		else if(cb==InvoiceBox)
			AddInvoicestoCombobox();
		else if((AddUnits!=null&&AddUnits.contains(cb))||cb==EnterUnit){
			cb.addItem("Select Unit");
			
			ResultSet RS=Parent.getDBHandler().MySQLSelect("SELECT Unit from Product group by Unit;", StatusAdd);
			
			while(RS.next())
				cb.addItem(RS.getString(1));
			RS.close();
		}
		else if((AddProd!=null&&AddProd.contains(cb))||cb==EnterProd){
			int i;
			ResultSet RS=null;
			cb.addItem("Select Product");
			if(cb!=EnterProd){
			i=AddProd.indexOf(cb);
			
			
			if(AddUnits.get(i).getSelectedIndex()>0){
				RS=Parent.getDBHandler().MySQLSelect("SELECT ProductName from Product where Unit='"+AddUnits.get(i).getSelectedItem().toString()+"';", StatusAdd);
				}
			}
			else if(EnterUnit.getSelectedIndex()>0)
				RS=Parent.getDBHandler().MySQLSelect("SELECT ProductName from Product where Unit='"+EnterUnit.getSelectedItem().toString()+"';", StatusAdd);
			
			if(RS!=null){
			while(RS.next())
				cb.addItem(RS.getString(1));
			RS.close();
			}
		}
	}

	
	public void AddInvoicestoCombobox(){
		if(InvoiceBox.getItemCount()>0)
			InvoiceBox.removeAllItems();
		for(int ctr=0;ctr<Invoices.size();ctr++)
			InvoiceBox.addItem(Invoices.get(ctr).getReceiptNum()+" "+Invoices.get(ctr).getCustomerName());
	}
	
	
	public void AddSalesRow(GBPane gb,int i){
		NewQuans.add(new JTextField("",5));
		AddUnits.add(new JComboBox());
		AddProd.add(new JComboBox());
		NewPrices.add(new JTextField("",5));
		
		try {
			setComboBoxItems(AddUnits.get(i));
			setComboBoxItems(AddProd.get(i));
		} catch (SQLException e) {
			// TODO Auto-generated catch block
		}
		
		
		gb.addComponent(NewQuans.get(i), 0, i+1, 1, 1, 0, 0,GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
		gb.addComponent(AddUnits.get(i), 1, i+1, 1, 1, 0, 0,GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
		gb.addComponent(AddProd.get(i), 2, i+1, 1, 1, 0, 0,GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
		gb.addComponent(NewPrices.get(i), 3, i+1, 1, 1, 0, 0,GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
		
		gb.paintAncestors();
		
		NewPrices.get(i).setEditable(false);
		
		AddUnits.get(i).addActionListener(this);
		AddProd.get(i).addActionListener(this);
		NewQuans.get(i).addFocusListener(this);
		NewPrices.get(i).addFocusListener(this);
		NewQuans.get(i).addKeyListener(this);
		NewPrices.get(i).addKeyListener(this);
	}
	
	public void AddInvoiceConfig(GBPane gb){
		gb.removeAll();
		
		gb.addComponent(new JLabel("Quantity "), 0, 0, 1, 1, 0, 0,GridBagConstraints.NONE, GridBagConstraints.WEST);
		gb.addComponent(new JLabel("Unit "), 1, 0, 1, 1, 0, 0,GridBagConstraints.NONE, GridBagConstraints.WEST);
		gb.addComponent(new JLabel("Product "),2, 0, 1, 1, 0, 0,GridBagConstraints.NONE, GridBagConstraints.WEST);
		gb.addComponent(new JLabel("Price "),3, 0, 1, 1, 0, 0,GridBagConstraints.NONE, GridBagConstraints.WEST);
		
		NewQuans=new ArrayList<JTextField>();
		AddUnits=new ArrayList<JComboBox>();
		AddProd=new ArrayList<JComboBox>();
		NewPrices=new ArrayList<JTextField>();
		
		AddSalesRow(gb, 0);
	}
	
	public void ResetInsertion(){
		AddInvoiceConfig(NewSales);
		NewCustomer.setText("");
        NewTotal.setText("");
        Newbal.setText("");
		RNumBox.setText("");
		NewSales.paintAncestors();
		InsertInvoice.setEnabled(false);
		Newbal.setEditable(false);
	}
	
	public void InsertReceipt(){
		String name;
		if(NewCustomer.getText().length()==0){
			name="";
			StatusAdd.setText("No  customer name");
		}
		else{
			name=NewCustomer.getText();
			int iRec=Parent.getDBHandler().MySQLinsert("Insert INTO Invoice values ('"+RNumBox.getText()+"',curDate(),'"+name+"',"+Newbal.getText()
					+");", StatusAdd),cnt;
			
			if(iRec>0){
				
				ResultSet RS;
				String id="";
				for(int ctr=0;ctr<AddUnits.size()-1;ctr++){
					RS=Parent.getDBHandler().MySQLSelect("SELECT ProductCode from Product where unit='"+AddUnits.get(ctr).getSelectedItem().toString()
						+"' AND productname='"+AddProd.get(ctr).getSelectedItem().toString()+"';", StatusAdd);
					
					try {
						
						while(RS.next())
							id=RS.getString(1);
						RS.close();
						cnt=Parent.getDBHandler().MySQLinsert("INSERT into Sale values(now()+'"+ctr+"',"+NewQuans.get(ctr).getText()
								+","+NewPrices.get(ctr).getText()+",'"+RNumBox.getText()+"','"+id+"');", StatusAdd);
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						StatusAdd.setText("Adding incomplete");
					}
					
				}
				
				ResetInsertion();
			}
		}
	}



        //method that changes the DayBox based on the month
	public void DayBoxConfig(int month){
		int limit,year=Integer.valueOf(YearBox.getSelectedItem().toString()),MaxDay=DayBox.getItemCount(),Day=DayBox.getSelectedIndex()+1;
		//Determine month to determine number of days
		if(month==0||month==2||month==4||month==6||month==7||month==9||month==11)
			limit =31;
		else if(month==1)
			if(year%4!=0)
				limit =28;
			else limit=29;
		else limit=30;

		DayBox.removeItemListener(this);
		//DayBox.setSelectedIndex(0);

		if(MaxDay<limit)
			for(int ctr=MaxDay+1;ctr<=limit;ctr++)
				DayBox.addItem(""+ctr);
		else if(MaxDay>limit){
			DayBox.removeAllItems();
			for(int ctr=1;ctr<=limit;ctr++)
				DayBox.addItem(""+ctr);
			while(Day>limit)
				Day--;
			DayBox.setSelectedItem(""+Day);
		}
		MonthBox.addItemListener(this);
		DayBox.addItemListener(this);
	}

	//Method that responds to the next and previous day buttons
	public void NextPrevDay(int change){
		int month;
		if(change>0){
			if(DayBox.getSelectedIndex()<DayBox.getItemCount()-change)
				DayBox.setSelectedIndex(DayBox.getSelectedIndex()+change);
			else if(MonthBox.getSelectedIndex()<MonthBox.getItemCount()-change){
				MonthBox.removeItemListener(this);
				MonthBox.setSelectedIndex(MonthBox.getSelectedIndex()+change);
				month=MonthBox.getSelectedIndex();

				DayBoxConfig(month);


				DayBox.setSelectedIndex(0);
			}
			else{
				YearBox.removeItemListener(this);
				YearBox.addItem(""+(Integer.valueOf(YearBox.getSelectedItem().toString())+1));
				YearBox.setSelectedIndex(YearBox.getItemCount()-1);
				MonthBox.setSelectedIndex(0);
				DayBox.setSelectedIndex(0);
				YearBox.addItemListener(this);

			}

		}
		else if(change<0){
			if(DayBox.getSelectedIndex()>0)
				DayBox.setSelectedIndex(DayBox.getSelectedIndex()+change);
			else if(MonthBox.getSelectedIndex()>0){
				MonthBox.removeItemListener(this);
				MonthBox.setSelectedIndex(MonthBox.getSelectedIndex()+change);
				month=MonthBox.getSelectedIndex();
				DayBoxConfig(month);


				DayBox.setSelectedIndex(DayBox.getItemCount()-1);
			}
			else if(YearBox.getSelectedIndex()>0)
				YearBox.setSelectedIndex(YearBox.getSelectedIndex()+change);
			else Statuslbl.setText("No more record in the previous Years");
		}
	}


	private double calculateNewInvoiceCost(){
		double sum=0;
		
		for(int ctr=0;ctr<NewPrices.size()-1;ctr++)
			sum+=Double.valueOf(NewPrices.get(ctr).getText());
		return sum;
	}

	
	private double getProductCost(String Unit,String Product) throws SQLException{
		ResultSet RS;
		double cost=1;
		RS=Parent.getDBHandler().MySQLSelect("SELECT unitPrice from Product where unit='"+Unit+"' AND ProductName='"+Product+"';", StatusAdd);
			while(RS.next())
				cost=RS.getDouble(1);
		
		return cost;
	}
	
	public void deleteSale(int i,JTextField txt){
		if(QuantityBoxes!=null&&(QuantityBoxes.contains(txt)||PriceBoxes.contains(txt))){
			Parent.getDBHandler().MySQLUpdate("DELETE from Sale where SaleID='"+Selected.getSales().get(i).getID()+"';", Statuslbl);
			Selected.getSales().remove(i);
			RecordpaneConfig(InvoiceBox.getSelectedIndex(), true);
			paintAnsestors(ViewPane);
			
		}
		else{
			
			//Remove from panel
			NewSales.remove(NewQuans.get(i));
			NewSales.remove(NewPrices.get(i));
			NewSales.remove(AddProd.get(i));
			NewSales.remove(AddUnits.get(i));
			
			//Remove sale from list
			NewQuans.remove(i);
			NewPrices.remove(i);
			AddUnits.remove(i);
			AddProd.remove(i);
			
			calculateNewInvoiceCost();
			NewSales.paintAncestors();
		}
	}
	
	public void deleteInvoice(){
		try {
			Parent.getDBHandler().MySQLUpdate("DELETE from Invoice where receiptNumber='"+Selected.getReceiptNum()+"';");
			Invoices.remove(Selected);
			//Must only delete invoices of the current date
			ChangeViewPaneContents("SELECT * from Invoice where dateofReceipt=CurDate()",true);
		} catch (SQLException SE) {
			Statuslbl.setText("Invoice was not deleted");
		}
	}
	
	
	@Override
	public void itemStateChanged(ItemEvent IE) {
		// TODO Auto-generated method stub
		Statuslbl.setText("");
                
                if(IE.getSource()==MonthBox){
			MonthBox.removeItemListener(this);
			DayBoxConfig(MonthBox.getSelectedIndex());
		}

		if(IE.getSource()==InvoiceBox&&InvoiceBox.getItemCount()>0){
			RecordpaneConfig(InvoiceBox.getSelectedIndex(),!MonthBox.isVisible());
			paintAnsestors(ViewPane);
                        Selected=Invoices.get(InvoiceBox.getSelectedIndex());
		}
		else if(IE.getSource()==DayBox||IE.getSource()==MonthBox||IE.getSource()==YearBox){
			
			//get the records from the selected date
			ChangeViewPaneContents("SELECT * from Invoice where dateofReceipt='"+
					YearBox.getSelectedItem().toString()+"-"+(MonthBox.getSelectedIndex()+1)+"-"+DayBox.getSelectedItem().toString()+"';",false);
		}
	}

	@Override
	public void actionPerformed(ActionEvent AE) {
		// TODO Auto-generated method stub
		
		Statuslbl.setText("");
		StatusAdd.setText("");
		
		if(AE.getSource()==UpdateBt){
			CL.show(Cnt, "Manage");
			
			//Must only modify sales of the current date
			ChangeViewPaneContents("SELECT * from Invoice where dateofReceipt=CurDate()",true);
			ManageViewPaneVisibility(false);
		}
		else if(AE.getSource()==ViewBt){
			CL.show(Cnt, "Manage");
			ChangeViewPaneContents("SELECT * from Invoice where dateofReceipt='"+
					YearBox.getSelectedItem().toString()+"-"+(MonthBox.getSelectedIndex()+1)+"-"+DayBox.getSelectedItem().toString()+"';",false);
			ManageViewPaneVisibility(true);
		}
		else if(AE.getSource()==AddMode)
			CL.show(Cnt, "Add");
		else if(AE.getSource()==DebtCheck)
			CL.show(Cnt, "Debt");
		else if(AE.getSource()==Next&&InvoiceBox.getSelectedIndex()<InvoiceBox.getItemCount()-1)
			InvoiceBox.setSelectedIndex(InvoiceBox.getSelectedIndex()+1);
		else if(AE.getSource()==Prev&&InvoiceBox.getSelectedIndex()>0)
			InvoiceBox.setSelectedIndex(InvoiceBox.getSelectedIndex()-1);
		else if(AE.getSource()==Prevday)
			NextPrevDay(-1);
		else if(AE.getSource()==Nextday)
			NextPrevDay(1);
		else if(AE.getSource()==DelInvoice)
			deleteInvoice();
		else if(AE.getSource()==EnterUnit)
			try {
				setComboBoxItems(EnterProd);
			} catch (SQLException e) {
				Statuslbl.setText("No product with that unit");
			}
		else if(AE.getSource()==EnterProd){
			double cost=1,q=1;
			String fid="",now=Parent.getDBHandler().getMysqlNow();
			if(Newbal!=null)
				Newbal.setEditable(true);

            if(EnterQuan.getText().length()>0)
                  try{
                      q=Double.valueOf(EnterQuan.getText());
                     }catch(NumberFormatException NE){
                       Statuslbl.setText("Type numbers for quantity");
                       q=1;
                       EnterQuan.setText(""+1);
                     }
			if(EnterUnit.getSelectedIndex()>0&&EnterQuan.getText().length()==0)
				EnterQuan.setText(""+1);
			
			if(EnterProd.getSelectedIndex()>0){
				try{
					
					ResultSet RS=Parent.getDBHandler().MySQLSelect("SELECT ProductCode from Product where unit='"+EnterUnit.getSelectedItem().toString()
							+"' AND productname='"+EnterProd.getSelectedItem().toString()+"';");
					
					while(RS.next())
						fid=RS.getString(1);
					RS.close();
					
					if(EnterQuan.getText().length()>0)
						cost=getProductCost(EnterUnit.getSelectedItem().toString(), EnterProd.getSelectedItem().toString())*Double.valueOf(EnterQuan.getText());
					else cost=getProductCost(EnterUnit.getSelectedItem().toString(), EnterProd.getSelectedItem().toString());
					
					
					EnterPrice.setText(""+cost);
					Parent.getDBHandler().MySQLinsert("INSERT into Sale values('"+now+"', "+EnterQuan.getText()
							+","+EnterPrice.getText()+","+Selected.getReceiptNum()+",'"+fid+"');");
					Selected.getSales().add(new Sale(now, EnterProd.getSelectedItem().toString(),EnterUnit.getSelectedItem().toString(), Double.valueOf(EnterQuan.getText()), cost, Selected));
				}catch (SQLException SE) {
					StatusAdd.setText("Price not found");
					cost=1;
				}
				EnterPrice.setEditable(true);
				EnterPrice.setText(""+cost);	//get the cost of the sale
				
				//Change the panel containing the recipt to correspond to the database
				RecordpaneConfig(InvoiceBox.getSelectedIndex(), true);
			
			}
		}
		else if(AddUnits!=null&&AddUnits.contains(AE.getSource())){
			int i=AddUnits.indexOf(AE.getSource());
			try {
				setComboBoxItems(AddProd.get(i));
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				StatusAdd.setText("No Product with that unit");
			}
		}
		else if(AddProd!=null&&AddProd.contains(AE.getSource())){
			int i=AddProd.indexOf(AE.getSource());
			double cost=0,q;

                        try{
                            q=Double.valueOf(NewQuans.get(i).getText());

                        }
                        catch(NumberFormatException NE){
                            q=1;
                            NewQuans.get(i).setText(""+q);
                        }

			if((NewQuans.get(i).getText().length()==0||q<=0)&&AddUnits.get(i).getSelectedIndex()>0)
				NewQuans.get(i).setText(""+1);
			
			if(AddProd.get(i).getSelectedIndex()>0){
				try{
					cost=getProductCost(AddUnits.get(i).getSelectedItem().toString(), AddProd.get(i).getSelectedItem().toString())*Double.valueOf(NewQuans.get(i).getText());
					
				}catch (SQLException SE) {
					StatusAdd.setText("Price not found");
					cost=0;
				}
				NewPrices.get(i).setEditable(true);
				NewPrices.get(i).setText(""+cost);	//get the cost of the sale
				
				if(i==AddProd.size()-1)
					AddSalesRow(NewSales, i+1);
				
				NewTotal.setText(""+calculateNewInvoiceCost());	//Update the total
				if(RNumBox.getText().length()>0){
					InsertInvoice.setEnabled(true);
					Newbal.setEditable(true);
				}
			}
			
		}
		else if(AE.getSource()==ResetInsert)
			ResetInsertion();
		else if(AE.getSource()==InsertInvoice)
			InsertReceipt();


	}

	@Override
	public void focusGained(FocusEvent FE) {
		int i;
		
		if(FE.getSource()==EnterQuan)
			if(EnterQuan.getText().length()>0)
				EnterQuan.setToolTipText(""+EnterQuan.getText());
			else EnterQuan.setToolTipText("1");
		
		else if(NewQuans.contains(FE.getSource())){
			i=NewQuans.indexOf(FE.getSource());
                        double d;
			if(NewQuans.get(i).getText().length()>0){
				try{
                                    d=Double.valueOf(NewQuans.get(i).getText());
                                    
                                }catch(NumberFormatException NE){
                                    d=1;
                                }
                            NewQuans.get(i).setToolTipText(""+d);
                        }
			else NewQuans.get(i).setToolTipText("1");
		}
		else if(NewPrices.contains(FE.getSource())){
			i=NewPrices.indexOf(FE.getSource());
			if(NewQuans.get(i).getText().length()>0)
				NewPrices.get(i).setToolTipText(""+NewPrices.get(i).getText());
			else NewPrices.get(i).setToolTipText("1");
		}
	}

	@Override
	public void focusLost(FocusEvent FE) {
		double cost=1;
		int i;
		
        Statuslbl.setFont(Parent.getWarningFont(Statuslbl));
        Statuslbl.setText("");
		if(QuantityBoxes!=null&&QuantityBoxes.contains(FE.getSource())){
			i=QuantityBoxes.indexOf(FE.getSource());
                        double q=Selected.getSales().get(i).getQuantity();

                        try{
                            q=Double.valueOf(QuantityBoxes.get(i).getText());
                        }catch(NumberFormatException NE){
                            q=Selected.getSales().get(i).getQuantity();
                            QuantityBoxes.get(i).setText(""+q);
                            Statuslbl.setText("Type numbers in quantity");
                        }


			if(QuantityBoxes.get(i).getText().length()==0){
				Statuslbl.setText("Do not put empty values on Quantity!");
				QuantityBoxes.get(i).setText(""+Selected.getSales().get(i).getQuantity());
			}
			else if(q<=0){
				Statuslbl.setText("Enter a number greater than 0!");
				QuantityBoxes.get(i).setText(""+Selected.getSales().get(i).getQuantity());
			} else
				try {
					Selected.getSales().get(i).setQuantity(Double.valueOf(QuantityBoxes.get(i).getText()));
					
					cost=getProductCost(Selected.getSales().get(i).getUnit(),Selected.getSales().get(i).getProduct())*Double.valueOf(QuantityBoxes.get(i).getText());
					Selected.getSales().get(i).setPrice(cost);
					PriceBoxes.get(i).setText(""+cost);
					Parent.getDBHandler().MySQLUpdate("UPDATE Sale SET Quantity="+QuantityBoxes.get(i).getText() +", price="+cost+" where SaleID='"+Selected.getSales().get(i).getID()+"';");
					TotalBox.setText(""+Selected.getTotal());
				} catch (SQLException SQLEx) {
					Statuslbl.setText("Error: "+SQLEx);
					QuantityBoxes.get(i).setText(Selected.getSales().get(i).getQuantity()+"");
				}
		}
		else if(PriceBoxes!=null&&PriceBoxes.contains(FE.getSource())){
			i=PriceBoxes.indexOf(FE.getSource());
			double p=Selected.getSales().get(i).getPrice();
			try{
				p=Double.valueOf(PriceBoxes.get(i).getText());
			}
			catch(NumberFormatException NE){
				p=Selected.getSales().get(i).getPrice();
                PriceBoxes.get(i).setText(""+Selected.getSales().get(i).getPrice());
                Statuslbl.setText("Type numbers only for prices");
			}
			
			if(PriceBoxes.get(i).getText().length()==0){
				Statuslbl.setText("Do not put empty values on Price!");
				PriceBoxes.get(i).setText(""+p);
			}
			else if(p<=0){
				Statuslbl.setText("Enter a number greater than 0!");
				PriceBoxes.get(i).setText(""+Selected.getSales().get(i).getPrice());
			} else
				try {
					Selected.getSales().get(i).setPrice(p);
					Parent.getDBHandler().MySQLUpdate("UPDATE Sale SET Price="+p+" where SaleID='"+Invoices.get(InvoiceBox.getSelectedIndex()).getSales().get(i).getID()+"';");
					TotalBox.setText(""+Selected.getTotal());
				} catch (Exception SQLEx) {
					Statuslbl.setText("Error: "+SQLEx);
					PriceBoxes.get(i).setText(Selected.getSales().get(i).getPrice()+"");
				}
		}
         else if(FE.getSource()==Customer&&InvoiceBox.getItemCount()>0){
                    try{
                        Selected.setCustomerName(Customer.getText());
                        InvoiceBox.setSelectedItem(Customer.getText());
                        Parent.getDBHandler().MySQLUpdate("UPDATE Invoice SET CustomerName='"+Customer.getText()+"' where receiptNumber='"+Selected.getReceiptNum()+"';");
                    } catch (SQLException SQLEx) {
                    	Statuslbl.setText("Error: "+SQLEx);
                    	Customer.setText(Selected.getCustomerName());
                    }
          }
         else if(FE.getSource()==BalanceBox&&InvoiceBox.getItemCount()>0){
        	 double bal=Selected.getBalance();
        	 
        	 try{
        		 bal=Double.valueOf(BalanceBox.getText());
        	 }catch(NumberFormatException NE){
        		 bal=Selected.getBalance();
        		 BalanceBox.setText(""+bal);
        		 Statuslbl.setText("Balance must be a number");
        	 }
        	 
        	 Selected.setBalance(bal);
             if(bal<0){
            	 Statuslbl.setText("Balance must not be less than zero");
            	 BalanceBox.setText(""+Selected.getBalance());
             }
        	 try{
                 Parent.getDBHandler().MySQLUpdate("UPDATE Invoice SET remainingBalance='"+bal+"' where receiptNumber='"+Selected.getReceiptNum()+"';");
             } catch (SQLException SQLEx) {
				Statuslbl.setText("Error: "+SQLEx);
				BalanceBox.setText(""+Selected.getBalance());
             }
         }
         else if(NewQuans.contains(FE.getSource())){
        	 double oldCost=0,q=1;
        	 i=NewQuans.indexOf(FE.getSource());
        	 
        	 try{
        		 q=Double.valueOf(NewQuans.get(i).getText());
        	 }catch(NumberFormatException NE){
        		 if(NewQuans.get(i).getToolTipText().length()>0){
                     q=1;
                     NewQuans.get(i).setText(NewQuans.get(i).getToolTipText());
                     StatusAdd.setText("Type only numbers for quantity");
                 }
                 else{
                     q=0;
                     NewQuans.get(i).setText("0");
                 }
        	 }
        	 
        	 if(NewQuans.get(i).getText().length()>0&&q<0){
        		 NewQuans.get(i).setText(""+(Double.valueOf(NewQuans.get(i).getText())*-1));
        		 StatusAdd.setText("No negative values for quantity");
        	 }
        	 if(NewQuans.get(i).getText().length()>0&&AddUnits.get(i).getSelectedIndex()>0&&AddProd.get(i).getSelectedIndex()>0){
        		 try{
        			 cost=getProductCost(AddUnits.get(i).getSelectedItem().toString(),AddProd.get(i).getSelectedItem().toString());
 					NewTotal.setText(""+(Double.valueOf(NewPrices.get(i).getText())-oldCost));	//Reduce the total
 				}
        		 catch (SQLException SE) {
 					StatusAdd.setText("Price not found");
 					NewQuans.get(i).setText(""+oldCost/cost);
 					cost=oldCost;
 					
 				}
        		cost*=q;
 				NewPrices.get(i).setText(""+cost);	//get the cost of the sale
 				NewTotal.setText(""+calculateNewInvoiceCost());	//Update the total
        	 }
        	 
         }
         else if(NewPrices.contains(FE.getSource())){
        	 double d;
        	 i=NewPrices.indexOf(FE.getSource());
        	 
        	 try{
        		 d=Double.valueOf(NewPrices.get(i).getText());
                         NewPrices.get(i).setText(""+d);
        	 }catch(NumberFormatException NE){
        		if(NewPrices.get(i).getToolTipText().length()>0){
                            d=1;
                            NewPrices.get(i).setText(NewPrices.get(i).getToolTipText());
                        }
                        else{
                            d=0;
                            NewPrices.get(i).setText("0");
                        }
        	}
        	 if(d<0)
        		 NewPrices.get(i).setText(""+(d*-1));
        	 if(NewPrices.get(i).getText().length()>0&&NewQuans.get(i).getText().length()>0&&AddUnits.get(i).getSelectedIndex()>0&&AddProd.get(i).getSelectedIndex()>0){
        		 try{
        			 cost=getProductCost(AddUnits.get(i).getSelectedItem().toString(),AddProd.get(i).getSelectedItem().toString());
 				}
        		 catch (SQLException SE) {
 					StatusAdd.setText("Price not found");
 					cost=0;
 				}
        		 cost*=Double.valueOf(NewQuans.get(i).getText());
 				NewPrices.get(i).setText(""+cost);	//get the cost of the sale
 				NewTotal.setText(""+calculateNewInvoiceCost());	//Update the total
        	 }
         }
         else if(FE.getSource()==Newbal){
        	 double bal=0,total;
        	 if(Newbal.getText().length()==0)
        		 Newbal.setText("0");
        	 else {
        		 try{
        			 bal=Double.valueOf(Newbal.getText());
        			 total=Double.valueOf(NewTotal.getText());
        			 if(bal>total){
        				 bal=total;
        				 StatusAdd.setText("Balance can not be greater than total");
        			 }
        		 }catch(NumberFormatException NE){
        			 bal=0;
        			 StatusAdd.setText("Balance must be number");
        		 }
        		 Newbal.setText(""+bal);
        	 }
         }
         else if(FE.getSource()==RNumBox){
        	 int Rnum=0;
        	 
        	 try{
        		 Rnum=Integer.valueOf(RNumBox.getText());
        	 }catch(NumberFormatException NE){
        		 Rnum=Integer.valueOf(Invoices.get(Invoices.size()-1).getReceiptNum())+1;
        		 RNumBox.setText(""+Rnum);
        		 Statuslbl.setText("Enter a valid whole number for Receipt number");
        		 RNumBox.requestFocus();
        	 }
        	 
        	 
        	 if(Rnum<0){
        		 Rnum*=-1;
        		 RNumBox.setText(""+Rnum);
        		 Statuslbl.setText("Enter positive numbers only");
        	 }
        	 
        	 
         }
         else if(FE.getSource()==LimBal){
        	 double d=0;
        	 
        	 try{
        		 d=Double.valueOf(LimBal.getText());
        		 if(d<0)
        			 d*=-1;
        	 }catch(NumberFormatException NE){
        		 d=0;
        		 
        	 }
        	 LimBal.setText(""+d);
        	 changeDebtPane(d);
        	 paintAnsestors(DebtPane);
         }
		
	}

	@Override
	public void keyPressed(KeyEvent KE) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void keyReleased(KeyEvent KE) {
		int i;
		
		if(KE.getSource()==Customer&&KE.getKeyCode()==KeyEvent.VK_ENTER)
			TotalBox.requestFocus();
		else if(KE.getSource()==TotalBox&&KE.getKeyCode()==KeyEvent.VK_ENTER)
			BalanceBox.requestFocus();
		else if(KE.getSource()==BalanceBox&&KE.getKeyCode()==KeyEvent.VK_ENTER)
			Customer.requestFocus();
		else if(KE.getSource()==NewCustomer){
			if(KE.getKeyCode()==KeyEvent.VK_ENTER)
                            RNumBox.requestFocus();

                        if(NewQuans.size()>1)
                            InsertInvoice.setEnabled(true);
                }
		else if(KE.getSource()==RNumBox){
			if(KE.getKeyCode()==KeyEvent.VK_ENTER)
                            Newbal.requestFocus();

                        if(RNumBox.getText().length()==0)
                            InsertInvoice.setEnabled(false);
                        else if(NewQuans.size()>1)
                            InsertInvoice.setEnabled(true);
                }
		else if(KE.getSource()==Newbal&&KE.getKeyCode()==KeyEvent.VK_ENTER)
			NewCustomer.requestFocus();
		else if(QuantityBoxes!=null&&QuantityBoxes.contains(KE.getSource())){
			i=QuantityBoxes.indexOf(KE.getSource());
			if(KE.getKeyCode()==KeyEvent.VK_ENTER)
				PriceBoxes.get(i).requestFocus();
			else if(QuantityBoxes.get(i).isEditable()&&KE.getKeyCode()==KeyEvent.VK_DELETE&&PriceBoxes.size()>1)
				deleteSale(i, QuantityBoxes.get(i));
		}
		else if(PriceBoxes!=null&&PriceBoxes.contains(KE.getSource())){
			i=PriceBoxes.indexOf(KE.getSource());
			
			if(KE.getKeyCode()==KeyEvent.VK_ENTER&&i<PriceBoxes.size()-1)
				QuantityBoxes.get(i+1).requestFocus();
			else if(PriceBoxes.get(i).isEditable()&&KE.getKeyCode()==KeyEvent.VK_DELETE&&PriceBoxes.size()>1)
				deleteSale(i, QuantityBoxes.get(i));
		}
		else if(NewQuans.contains(KE.getSource())){
			i=NewQuans.indexOf(KE.getSource());
			if(KE.getKeyCode()==KeyEvent.VK_ENTER)
				NewPrices.get(i).requestFocus();
			else if(i<NewQuans.size()-1&&KE.getKeyCode()==KeyEvent.VK_DELETE)
				deleteSale(i, NewQuans.get(i));
		}
		else if(NewPrices.contains(KE.getSource())){
			i=NewPrices.indexOf(KE.getSource());
			if(KE.getKeyCode()==KeyEvent.VK_ENTER&&i<NewPrices.size()-1)
				NewQuans.get(i+1).requestFocus();
		}
		else if(KE.getSource()==LimBal&&KE.getKeyCode()==KeyEvent.VK_ENTER)
			ViewBt.requestFocus();
	}

	@Override
	public void keyTyped(KeyEvent KE) {
		// TODO Auto-generated method stub
		
	}
	
}
